package com.ziq.zcamp.community

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.Rect
import android.graphics.Typeface
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.SpanUtils
import com.ziq.base.base.BaseFragment
import com.ziq.base.extension.*
import com.ziq.zcamp.R
import com.ziq.zcamp.activities.ActivitiesDetailsActivity
import com.ziq.zcamp.bean.activities.ActivitiesInfo
import com.ziq.zcamp.databinding.FragmentCommunityActivitiesBinding
import com.ziq.zcamp.databinding.ItemActivitiesCommonListBinding
import com.ziq.zcamp.databinding.ItemActivitiesRecommendListBinding
import com.ziq.zcamp.util.ImageUtil
import com.ziq.zcamp.util.TimeUtil
import com.ziq.zcamp.view.StatusView
import dagger.hilt.android.AndroidEntryPoint
import java.text.DecimalFormat
import java.util.*

@AndroidEntryPoint
class CommunityActivitiesFragment : BaseFragment(R.layout.fragment_community_activities){

    val mViewModel: CommunityActivitiesViewModel by viewModels()
    private val binding : FragmentCommunityActivitiesBinding? by binding()
    private var current = 0
    var hasShow = false
    private val commonAdapter by lazy { CommonAdapter(requireContext()) }
    private val recommendAdapter by lazy { RecommendAdapter(requireContext(),) }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding?.root
        binding?.apply {

            refreshLayout.setOnRefreshListener {
                mViewModel.requestRecommendList()
                mViewModel.requestCommonList(true)
            }
            refreshLayout.setOnLoadMoreListener {
                mViewModel.requestCommonList(false)
            }


            rvActivitiesCommonList.layoutManager = LinearLayoutManager(context)
            rvActivitiesCommonList.adapter = commonAdapter
            mViewModel.commonActivitiesList.observe(this@CommunityActivitiesFragment){
                commonAdapter.updateData(it)
            }

            rvActivitiesRecommendList.adapter = recommendAdapter
            rvActivitiesRecommendList.addItemDecoration(object : RecyclerView.ItemDecoration() {
                override fun getItemOffsets(
                    outRect: Rect,
                    view: View,
                    parent: RecyclerView,
                    state: RecyclerView.State
                ) {
                    super.getItemOffsets(outRect, view, parent, state)
                    outRect.left = 10.dp
                    if (parent.getChildAdapterPosition(view)==(recommendAdapter.dataList.size-1)){
                        outRect.right = 10.dp
                    }
                }
            })
            rvActivitiesRecommendList.layoutManager = LinearLayoutManager(context,
                LinearLayoutManager.HORIZONTAL,false)

            mViewModel.recommendedActivitiesList.observe(this@CommunityActivitiesFragment){
                recommendAdapter.updateData(it)
            }

        }

        mViewModel.statusShow.observe(viewLifecycleOwner) {
            when (it) {
                StatusView.IDLE -> {
                    binding?.statusView?.setStatus(StatusView.IDLE)
                    binding?.refreshLayout?.finishRefresh()
                    binding?.refreshLayout?.finishLoadMore()
                }
                StatusView.LOADING -> {
                    binding?.statusView?.setStatus(StatusView.LOADING)
                }
                StatusView.NO_DATA -> {
                    binding?.statusView?.setStatus(
                        StatusView.NO_DATA,
                        isCenter = false,
                        marginTop = 86.dp,
                        imgSrc = R.drawable.pic_no_content_camp,
                        imgWidth = 235.dp,
                        imgHeight = 151.dp,
                        msg = "敬请期待"
                    )
                    binding?.refreshLayout?.finishRefresh()
                    binding?.refreshLayout?.finishLoadMore()
                }
                StatusView.NET_ERROR -> {
                    binding?.statusView?.setStatus(
                        StatusView.NET_ERROR,
                        isCenter = false,
                        marginTop = 86.dp,
                        updateActionBtn = { btn ->
                            btn.click {
                                mViewModel.requestCommonList(true)
                                mViewModel.requestRecommendList()
                            }
                        })
                    binding?.refreshLayout?.finishRefresh()
                    binding?.refreshLayout?.finishLoadMore()
                }
            }
        }
        mViewModel.hasMoreData.observe(viewLifecycleOwner){
            it?.let {
                binding?.refreshLayout?.setNoMoreData(!it)
            }
        }

        mViewModel.recommendShow.observe(viewLifecycleOwner){
            it?.let {
                binding?.ctlActivitiesRecommend?.visibility = if (it) View.VISIBLE else View.GONE
                commonAdapter.recommendIsShow = it
                commonAdapter.notifyItemChanged(0)
            }
        }

    }

    override fun onResume() {
        super.onResume()
        if (!hasShow){
            hasShow = true
            mViewModel.requestRecommendList()
            mViewModel.requestCommonList(true)
        }
    }

    /**
     * 推荐的活动列表
     */
    private class RecommendAdapter(val context : Context)
        : RecyclerView.Adapter<BindingViewHolder<ItemActivitiesRecommendListBinding>>(){

        init {
            setHasStableIds(true)
        }

        val dataList : MutableList<ActivitiesInfo> = mutableListOf()

        fun updateData(list : List<ActivitiesInfo>){
            dataList.clear()
            dataList.addAll(list)
            notifyDataSetChanged()
        }

        override fun getItemCount(): Int {
            return dataList.size
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): BindingViewHolder<ItemActivitiesRecommendListBinding> {
            return createBindingViewHolder(parent)
        }

        override fun onBindViewHolder(
            holder: BindingViewHolder<ItemActivitiesRecommendListBinding>,
            position: Int
        ) {
            val item = dataList[position]
            val binding = ItemActivitiesRecommendListBinding.bind(holder.itemView)
            val imageInfo = item.images?.let {
                if (it.isNotEmpty()){
                    it[0]
                }else{
                    null
                }
            }
            ImageUtil.updateImageFromNetwork(binding.ivActivitiesRecommendPoster, imageInfo?.url,imageInfo?.width?:0 , imageInfo?.height?:0 )
            binding.tvActivitiesRecommendName.text = item.title
            item.start_time.let {
                if (it!=null){
                    binding.tvActivitiesRecommendTime.text = TimeUtil.yyyy_MM_dd_SPOT_FORMATTER_CN.format(
                        Date((item.start_time?:0)*1000)
                    )
                }else{
                    binding.tvActivitiesRecommendTime.text = "--:--"
                }

            }

            binding.clActivitiesRecommendRoot.click {
                ActivitiesDetailsActivity.open(context,item.id?:0,item,ActivitiesDetailsActivity.SOURCE_LIST)
            }
        }
    }

    /**
     * 普通的活动列表
     */
    private class CommonAdapter(val context : Context)
        : RecyclerView.Adapter<BindingViewHolder<ItemActivitiesCommonListBinding>>(){

        var recommendIsShow = false

        init {
            setHasStableIds(true)
        }

        val dataList : MutableList<ActivitiesInfo> = mutableListOf()

        fun updateData(list : List<ActivitiesInfo>){
            dataList.clear()
            dataList.addAll(list)
            notifyDataSetChanged()
        }

        override fun getItemCount(): Int {
            return dataList.size
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): BindingViewHolder<ItemActivitiesCommonListBinding> {
            return createBindingViewHolder(parent)
        }

        override fun onBindViewHolder(
            holder: BindingViewHolder<ItemActivitiesCommonListBinding>,
            position: Int
        ) {
            val item = dataList[position]
            val binding = ItemActivitiesCommonListBinding.bind(holder.itemView)
            if (position == 0 && !recommendIsShow){
                binding.vActivitiesListFirstMask.visibility = View.VISIBLE
            }else{
                binding.vActivitiesListFirstMask.visibility = View.GONE
            }

            val imageInfo = item.images?.let {
                if (it.isNotEmpty()){
                    it[0]
                }else{
                    null
                }
            }
            ImageUtil.updateImageFromNetwork(binding.ivActivitiesListPoster,imageInfo?.url, imageInfo?.width?:0,imageInfo?.height?:0)

            binding.tvActivitiesListName.text = item.title
            var timeStr = ""
            timeStr = if (item.start_time == null && item.end_time == null){
                "--:--"
            }else if (item.start_time != null && item.end_time == null){
                TimeUtil.yyyy_MM_dd_SPOT_FORMATTER_CN.format((item.start_time!!)*1000)
            }else{
                if (TimeUtil.isSameDay(item.start_time!!*1000,item.end_time!!*1000)){
                    TimeUtil.yyyy_MM_dd_SPOT_FORMATTER_CN.format((item.start_time!!)*1000)
                }else{
                    if (TimeUtil.isSameYear(item.start_time!!*1000,item.end_time!!*1000)){
                        "${TimeUtil.yyyy_MM_dd_SPOT_FORMATTER_CN.format((item.start_time!!)*1000)}-${TimeUtil.MM_dd_SPOT_FORMATTER_CN.format((item.end_time!!)*1000)}"
                    }else{
                        "${TimeUtil.yyyy_MM_dd_SPOT_FORMATTER_CN.format((item.start_time!!)*1000)}-${TimeUtil.yyyy_MM_dd_SPOT_FORMATTER_CN.format((item.end_time!!)*1000)}"
                    }
                }
            }
            binding.tvActivitiesListTime.text= timeStr
            binding.tvActivitiesListLocation.text = item.location_addr
            setPriceText(binding.tvActivitiesListPrice,item.free_type == 1, DecimalFormat("0.00").format((item?.price_range?.minOrNull()?:0) / 100f))

            val show = if (item?.act_status == 3){
                View.VISIBLE
            }else{
                View.GONE
            }
            binding.ivActivitiesListFinishSign.visibility = show
            binding.tvActivitiesListFinishSign.visibility = show

            binding.vActivitiesListContentMask.click {
                ActivitiesDetailsActivity.open(context,item.id?:0,item,ActivitiesDetailsActivity.SOURCE_LIST)
            }
        }


        @SuppressLint("RestrictedApi")
        private fun setPriceText(text : TextView, isFree : Boolean, content : String) {
            if (isFree){
                SpanUtils.with(text)
                    .append("免费").setForegroundColor(Color.parseColor("#729D55")).setTypeface(
                        Typeface.DEFAULT_BOLD).setFontSize(13.dp)
                    .create()
            }else{
                SpanUtils.with(text)
                    .append("￥").setForegroundColor(Color.parseColor("#AF8B6C")).setFontSize(12.dp)
                    .append(content).setForegroundColor(Color.parseColor("#AF8B6C")).setFontSize(22.dp)
                    .append(" 起").setForegroundColor(Color.parseColor("#AF8B6C")).setFontSize(12.dp)
                    .create()
            }
        }
    }

}